package com.example.backendhjh.service;

import com.example.backendhjh.dto.ProductDTO;
import com.example.backendhjh.dto.ProductResponseDTO;
import com.example.backendhjh.entity.Product;
import com.example.backendhjh.exception.ApiException;
import com.example.backendhjh.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductService {

    private final ProductMapper productMapper;
    private final UserService userService;

    @Autowired
    public ProductService(ProductMapper productMapper, UserService userService) {
        this.productMapper = productMapper;
        this.userService = userService;
    }

    @Transactional
    public ProductResponseDTO createProduct(ProductDTO productDTO) {
        // 验证卖家是否存在
        userService.getUserById(productDTO.getSellerId());

        Product product = new Product();
        product.setName(productDTO.getName());
        product.setDescription(productDTO.getDescription());
        product.setPrice(productDTO.getPrice());
        product.setStock(productDTO.getStock());
        product.setSellerId(productDTO.getSellerId());
        product.setCategory(productDTO.getCategory());
        product.setImageUrl(productDTO.getImageUrl());
        product.setCreatedAt(LocalDateTime.now());

        int result = productMapper.insert(product);
        if (result <= 0) {
            throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "商品创建失败");
        }

        return convertToResponseDTO(product);
    }

    public ProductResponseDTO getProductById(Long id) {
        Product product = productMapper.findById(id);
        if (product == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "商品不存在");
        }
        return convertToResponseDTO(product);
    }

    public List<ProductResponseDTO> getAllProducts() {
        List<Product> products = productMapper.findAll();
        return products.stream()
                .map(this::convertToResponseDTO)
                .collect(Collectors.toList());
    }

    public List<ProductResponseDTO> searchProducts(String keyword, String category) {
        List<Product> products = productMapper.searchProducts(keyword, category);
        return products.stream()
                .map(this::convertToResponseDTO)
                .collect(Collectors.toList());
    }

    @Transactional
    public ProductResponseDTO updateProduct(Long id, ProductDTO productDTO) {
        Product existingProduct = productMapper.findById(id);
        if (existingProduct == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "商品不存在");
        }

        // 更新商品信息
        if (productDTO.getName() != null) {
            existingProduct.setName(productDTO.getName());
        }
        if (productDTO.getDescription() != null) {
            existingProduct.setDescription(productDTO.getDescription());
        }
        if (productDTO.getPrice() != null) {
            existingProduct.setPrice(productDTO.getPrice());
        }
        if (productDTO.getStock() != null) {
            existingProduct.setStock(productDTO.getStock());
        }
        if (productDTO.getCategory() != null) {
            existingProduct.setCategory(productDTO.getCategory());
        }
        if (productDTO.getImageUrl() != null) {
            existingProduct.setImageUrl(productDTO.getImageUrl());
        }

        int result = productMapper.update(existingProduct);
        if (result <= 0) {
            throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "商品更新失败");
        }

        return convertToResponseDTO(existingProduct);
    }

    @Transactional
    public void deleteProduct(Long id) {
        Product product = productMapper.findById(id);
        if (product == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "商品不存在");
        }

        int result = productMapper.delete(id);
        if (result <= 0) {
            throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "商品删除失败");
        }
    }

    private ProductResponseDTO convertToResponseDTO(Product product) {
        ProductResponseDTO dto = new ProductResponseDTO();
        dto.setId(product.getId());
        dto.setName(product.getName());
        dto.setDescription(product.getDescription());
        dto.setPrice(product.getPrice());
        dto.setStock(product.getStock());
        dto.setSellerId(product.getSellerId());
        dto.setSellerName(userService.getUserById(product.getSellerId()).getUsername());
        dto.setCreatedAt(product.getCreatedAt());
        dto.setCategory(product.getCategory());
        dto.setImageUrl(product.getImageUrl());
        return dto;
    }
}